package logger

import (
	"os"
	"path/filepath"
	"time"

	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var Logger *zap.Logger

// InitLogger 初始化日志系统
func InitLogger() {
	// 创建日志目录
	if err := os.MkdirAll("logs", 0755); err != nil {
		panic("Failed to create logs directory: " + err.Error())
	}

	// 获取当前时间作为日志文件名的一部分
	now := time.Now()
	logFileName := now.Format("2006-01-02") + ".log"
	logFilePath := filepath.Join("logs", logFileName)

	// 配置日志输出
	writeSyncer := getLogWriter(logFilePath)
	encoder := getEncoder()

	// 创建核心
	core := zapcore.NewCore(
		encoder,
		zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), writeSyncer),
		zapcore.DebugLevel,
	)

	// 创建Logger
	Logger = zap.New(core, zap.AddCaller())

	// 替换全局Logger
	zap.ReplaceGlobals(Logger)
}

// getEncoder 获取日志编码器
func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
	return zapcore.NewJSONEncoder(encoderConfig)
}

// getLogWriter 获取日志写入器
func getLogWriter(filePath string) zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   filePath,
		MaxSize:    10,    // 每个日志文件最大10MB
		MaxBackups: 5,     // 最多保留5个备份
		MaxAge:     30,    // 最多保留30天
		Compress:   true,  // 压缩旧日志文件
	}
	return zapcore.AddSync(lumberJackLogger)
}

// Debug 记录Debug级别日志
func Debug(msg string, fields ...zap.Field) {
	Logger.Debug(msg, fields...)
}

// Info 记录Info级别日志
func Info(msg string, fields ...zap.Field) {
	Logger.Info(msg, fields...)
}

// Warn 记录Warn级别日志
func Warn(msg string, fields ...zap.Field) {
	Logger.Warn(msg, fields...)
}

// Error 记录Error级别日志
func Error(msg string, fields ...zap.Field) {
	Logger.Error(msg, fields...)
}

// Fatal 记录Fatal级别日志
func Fatal(msg string, fields ...zap.Field) {
	Logger.Fatal(msg, fields...)
}

// Panic 记录Panic级别日志
func Panic(msg string, fields ...zap.Field) {
	Logger.Panic(msg, fields...)
}

// WithField 创建带有字段的Logger
func WithField(key string, value interface{}) *zap.Logger {
	return Logger.With(zap.Any(key, value))
}

// WithFields 创建带有多个字段的Logger
func WithFields(fields map[string]interface{}) *zap.Logger {
	zapFields := make([]zap.Field, 0, len(fields))
	for k, v := range fields {
		zapFields = append(zapFields, zap.Any(k, v))
	}
	return Logger.With(zapFields...)
}

// WithError 创建带有错误的Logger
func WithError(err error) *zap.Logger {
	return Logger.With(zap.Error(err))
}